package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.UUID;

/**
 * @author 刘昱江
 * 时间 2021/5/11
 */
@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> findAll() {
        return userMapper.selectList(null);
    }

    @Override
    public String login(User user) {
        String password = user.getPassword();
        byte[] passByte = password.getBytes();
        String m5pass = DigestUtils.md5DigestAsHex(passByte);
        user.setPassword(m5pass);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>(user);
        User userDB = userMapper.selectOne(queryWrapper);
        if(userDB == null) {
            return null;
        }
        String token = UUID.randomUUID().toString().replace("-", "");
        return token;
    }

    @Override
    public PageResult userList(PageResult pageResult) {
        Integer pageNum = pageResult.getPageNum();
        Integer pageSize = pageResult.getPageSize();

        Page<User> page =new Page<>(pageNum,pageSize);
        String query = pageResult.getQuery();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        boolean flag = StringUtils.hasLength(query);
        queryWrapper.like(flag,"username", query);
        page = userMapper.selectPage(page, queryWrapper);
        pageResult.setRows(page.getRecords()).setTotal(page.getTotal());
        System.out.println(pageResult);
        return pageResult;
    }

    @Override
    @Transactional
    public void addUser(User user) {
        byte[] bytes = user.getPassword().getBytes();
        user.setPassword(DigestUtils.md5DigestAsHex(bytes));

        user.setStatus(true);
        userMapper.insert(user);

    }
}
